package com.example.demo.leetcode.top100;

import java.util.LinkedList;
import java.util.List;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _58组合总和
 * @description
 * @date 2023/06/21 10:09
 * <p>
 * ******************************************************
 */
public class _58组合总和 {

    List<List<Integer>> result = new LinkedList<>();
    LinkedList<Integer> trace = new LinkedList<>();
    Integer traceSum = 0;

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backtrack(candidates, target, 0);
        return result;
    }

    private void backtrack(int[] candidates, int target, int start) {

        if (traceSum == target) {
            result.add(new LinkedList<>(trace));
        }

        for (int i = start; i < candidates.length; i++) {
            int candidate = candidates[i];
            if (candidate + traceSum > target) {
                continue;
            }
            trace.add(candidate);
            traceSum += candidate;
            backtrack(candidates, target, i);
            Integer rem = trace.removeLast();
            traceSum -= rem;
        }

    }

}
